<script setup lang="ts">
import { Close, Select, ArrowDown } from "@element-plus/icons-vue";
import { buyerGoodsPage } from "@/api/goods";
import { onMounted, ref, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "~/store/useUser";
import { useImageCache } from "~/composables/useImageCache";

// 使用图片缓存功能
const { getCoverImage, preloadImages } = useImageCache();

// 只在客户端加载 ldrs
if (process.client) {
  const { tailChase } = await import('ldrs')
  tailChase.register()
}

const userStore = useUserStore();
const isLogin = ref(false);
const userInfo = ref({});

useSeoMeta({
  title: "商品列表 - 技能猴子",
  ogTitle: "商品列表 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

interface FormDataType {
  searchWord?: string;
  firstTypeId?: number;
  secondTypeId?: number[];
  sellerLevel?: number[];
  sellerOnline?: number[];
  minAmouont?: number;
  maxAmouont?: number;
  orderBy: number;
  pageSize: number;
  pageNum: number;
}

interface GoodsItem {
  id: number;
  name: string;
}

interface GoodsResponse {
  total: number;
  rows: GoodsItem[];
}

// 选择分类
const typeId = ref(0);
const typeLabel = ref("推荐");
const childrenTypes = ref<Array<{ id: number; name: string }>>([]);

// 卖家级别
const salerLevels = ref([
  {
    label: "级别最高得卖家",
    value: 3,
  },
  {
    label: "2级卖家",
    value: 2,
  },
  {
    label: "3级卖家",
    value: 1,
  },
  {
    label: "新卖家",
    value: 0,
  },
]);

// 卖家状态
const online = ref([
  {
    label: "当前在线",
    value: 1,
  },
  {
    label: "已离线",
    value: 0,
  },
]);

// 开启服务时间
const deliverDays = ref([
  {
    label: "最快24小时",
    value: 1,
  },
  {
    label: "最多3天",
    value: 3,
  },
  {
    label: "最多7天",
    value: 7,
  },
  {
    label: "任何时候",
    value: 0,
  },
]);

const route = useRoute();
const router = useRouter();

// 添加keyword变量定义
const keyword = ref("");

// 添加来源追踪变量
const isFromHomeSearch = ref(false);

const formData = ref<FormDataType>({
  pageNum: 1,
  pageSize: 20,
  orderBy: 1,
  searchWord: "",
  firstTypeId: undefined,
  secondTypeId: [],
  sellerLevel: [],
  sellerOnline: [],
  minAmouont: 0,
  maxAmouont: 0,
});

// 客户端状态检查
const isClient = ref(false);
onMounted(() => {
  // 初始化用户信息
  isLogin.value = userStore.isLogin;
  userInfo.value = { ...userStore.getUserInfo };
  
  console.log('Commodity page mounted - isLogin:', isLogin.value);
  console.log('Commodity page mounted - userInfo:', userInfo.value);
  
  // 标记为客户端
  isClient.value = true;

  const query = route.query;
  if (Object.keys(query).length > 0) {
    const params = {} as any;
    
    // 检查是否来自首页搜索
    isFromHomeSearch.value = query.source === 'homeSearch';
    
    if (query.pageNum) params.pageNum = Number(query.pageNum);
    if (query.pageSize) params.pageSize = Number(query.pageSize);
    if (query.orderBy) params.orderBy = Number(query.orderBy);
    if (query.searchWord) params.searchWord = decodeURIComponent(query.searchWord as string);
    if (query.keyword) {
      params.searchWord = decodeURIComponent(query.keyword as string);
      keyword.value = decodeURIComponent(query.keyword as string);
    }
    
    // 如果来自首页搜索，不应用任何类型参数
    if (!isFromHomeSearch.value) {
      if (query.firstTypeId) params.firstTypeId = Number(query.firstTypeId);
      if (query.secondTypeId) {
        params.secondTypeId = Array.isArray(query.secondTypeId)
          ? query.secondTypeId.map(Number)
          : [Number(query.secondTypeId)];
      }
    }
    
    if (query.sellerLevel) {
      params.sellerLevel = Array.isArray(query.sellerLevel)
        ? query.sellerLevel.map(Number)
        : [Number(query.sellerLevel)];
    }
    if (query.sellerOnline) {
      params.sellerOnline = Array.isArray(query.sellerOnline)
        ? query.sellerOnline.map(Number)
        : [Number(query.sellerOnline)];
    }
    if (query.minAmouont) params.minAmouont = Number(query.minAmouont);
    if (query.maxAmouont) params.maxAmouont = Number(query.maxAmouont);

    formData.value = {
      ...formData.value,
      ...params,
    };
    
    // 立即更新URL参数以保持同步
    updateUrlParams();
  }
  getGoodsList();
});

// 监听用户状态变化
watch(() => userStore.isLogin, (newVal) => {
  isLogin.value = newVal;
  console.log('Commodity page login status changed:', newVal);
}, { immediate: true });

watch(() => userStore.getUserInfo, (newVal) => {
  userInfo.value = { ...newVal };
  console.log('Commodity page updated userInfo:', userInfo.value);
}, { deep: true, immediate: true });

const updateUrlParams = () => {
  const query = {} as any;
  const data = formData.value;

  if (data.pageNum !== 1) query.pageNum = data.pageNum;
  if (data.pageSize !== 20) query.pageSize = data.pageSize;
  if (data.orderBy !== 1) query.orderBy = data.orderBy;
  if (data.searchWord) query.searchWord = encodeURIComponent(data.searchWord);
  
  // 如果来自首页搜索，不添加任何类型参数到URL
  if (!isFromHomeSearch.value) {
    if (data.firstTypeId) query.firstTypeId = data.firstTypeId;
    if (data.secondTypeId?.length) query.secondTypeId = data.secondTypeId;
  }
  
  if (data.sellerLevel?.length) query.sellerLevel = data.sellerLevel;
  if (data.sellerOnline?.length) query.sellerOnline = data.sellerOnline;
  if (data.minAmouont) query.minAmouont = data.minAmouont;
  if (data.maxAmouont) query.maxAmouont = data.maxAmouont;
  
  // 保留来源标识
  if (isFromHomeSearch.value) {
    query.source = 'homeSearch';
  }

  router.push({ query });
};

const total = ref(null);
const records = ref<GoodsItem[]>([]);
const loading = ref(false);
const getGoodsList = async () => {
  try {
    loading.value = true;
    const cloneFormData = { ...formData.value } as FormDataType;
    
    // 清理空数组和无效值
    if (cloneFormData.secondTypeId && cloneFormData.secondTypeId.length === 0) {
      delete cloneFormData.secondTypeId;
    }
    if (cloneFormData.sellerLevel && cloneFormData.sellerLevel.length === 0) {
      delete cloneFormData.sellerLevel;
    }
    if (cloneFormData.sellerOnline && cloneFormData.sellerOnline.length === 0) {
      delete cloneFormData.sellerOnline;
    }
    if (!cloneFormData.minAmouont) {
      delete cloneFormData.minAmouont;
    }
    if (!cloneFormData.maxAmouont) {
      delete cloneFormData.maxAmouont;
    }
    if (!cloneFormData.searchWord) {
      delete cloneFormData.searchWord;
    }
    if (!cloneFormData.firstTypeId) {
      delete cloneFormData.firstTypeId;
    }
    
    const data = (await buyerGoodsPage(cloneFormData)) as GoodsResponse;
    total.value = data.total;
    
    // 预加载商品封面图片
    if (data.rows && data.rows.length > 0) {
      // 提取所有商品的封面图片ossId
      const coverPicOssIds = data.rows
        .map(item => item.coverPic)
        .filter(coverPic => coverPic && !coverPic.includes('http'))
        .map(coverPic => coverPic.split(',')[0]);
      
      // 预加载图片
      if (coverPicOssIds.length > 0) {
        await preloadImages(coverPicOssIds);
      }
      
      // 处理图片URL，避免模板中重复调用getCoverImage
      records.value = data.rows.map(item => ({
        ...item,
        processedCoverPic: getCoverImage(item.coverPic) || item.coverPic
      }));
    } else {
      records.value = data.rows;
    }
    
    window.scrollTo(0, 0);

    // 更新URL参数
    updateUrlParams();
  } catch (e) {
    console.log(e);
  } finally {
    loading.value = false;
  }
};
const currentChange = (pageNum: number) => {
  formData.value.pageNum = pageNum;
  getGoodsList();
};
// 卖家等级筛选
const salerLevelsChange = (value: number) => {
  formData.value = {
    ...formData.value,
    sellerLevel: formData.value.sellerLevel || [],
  };
  
  const currentSellerLevel = formData.value.sellerLevel;
  const findIndex = currentSellerLevel.findIndex((item) => item === value);
  
  if (findIndex !== -1) {
    currentSellerLevel.splice(findIndex, 1);
  } else {
    currentSellerLevel.push(value);
  }
  
  if (currentSellerLevel && currentSellerLevel.length === 0) {
    const { sellerLevel, ...rest } = formData.value;
    formData.value = rest;
  }
  getGoodsList();
};
// 卖家在线状态筛选
const onlineChange = (value: number) => {
  formData.value = {
    ...formData.value,
    sellerOnline: formData.value.sellerOnline || [],
  };
  
  const currentSellerOnline = formData.value.sellerOnline;
  const findIndex = currentSellerOnline.findIndex((item) => item === value);
  
  if (findIndex !== -1) {
    currentSellerOnline.splice(findIndex, 1);
  } else {
    currentSellerOnline.push(value);
  }
  
  if (currentSellerOnline.length === 0) {
    const { sellerOnline, ...rest } = formData.value;
    formData.value = rest;
  }
  getGoodsList();
};
// 排序
const switchOrder = (orderBy: number) => {
  formData.value.orderBy = orderBy;
  getGoodsList();
};
const selectConfirm = () => {
  console.log(formData.value.minAmouont);
  if (!formData.value.minAmouont) {
    formData.value.minAmouont = 0;
  }
  getGoodsList();
};
const reset = ref(true);
const clearSetting = (index: number) => {
  switch (index) {
    case 1:
      formData.value.firstTypeId = undefined;
      formData.value.secondTypeId = [];
      break;
    case 2:
      delete formData.value.sellerLevel;
      delete formData.value.sellerOnline;
      reset.value = false;
      setTimeout(() => {
        reset.value = true;
      });
      break;
    case 3:
      delete formData.value.minAmouont;
      delete formData.value.maxAmouont;
      break;
  }
};
// 查看更多
const showMoreList = computed(() => {
  if (showMore.value) return childrenTypes.value;
  return childrenTypes.value.slice(0, 8);
});
const showMore = ref(false);
const openMore = () => {
  showMore.value = true;
};
// 获取当前是不是选了商品分类
const isSelectGoodsType = computed(() => {
  return !!formData.value.firstTypeId;
});
// 获取当前选中的商品分类列表
const selectGoodsTypeList = computed(() => {
  if (!formData.value.secondTypeId || formData.value.secondTypeId.length === 0) return [];
  return childrenTypes.value.filter((item) =>
    formData.value.secondTypeId.includes(item.id)
  );
});
// 获取当前已选中的卖家级别
const selectSalerLevels = computed(() => {
  if (!formData.value.sellerLevel) return [];
  return salerLevels.value.filter((item) =>
    formData.value.sellerLevel.includes(item.value)
  );
});
// 获取当前已选中的卖家状态
const selectOnline = computed(() => {
  if (!formData.value.sellerOnline) return [];
  return online.value.filter((item) => formData.value.sellerOnline.includes(item.value));
});
// 删除选中的商品分类
const delSelect = (index: number, item: any) => {
  if (index === 1) {
    formData.value.secondTypeId = formData.value.secondTypeId.filter(
      (id) => id !== item.id
    );
    getGoodsList();
    return;
  }
  if (index === 2) {
    console.log(formData.value.sellerLevel, item);
    formData.value.sellerLevel = formData.value.sellerLevel.filter(
      (id) => id != item.value
    );
    getGoodsList();
    return;
  }
  if (index === 3) {
    formData.value.sellerOnline = formData.value.sellerOnline.filter((id) => id !== item.value);
    getGoodsList();
    return;
  }
  if (index === 4) {
    delete formData.value.minAmouont;
    delete formData.value.maxAmouont;
    getGoodsList();
    return;
  }
};
// 头部搜索
const headerSearch = (keywordText: string) => {
  formData.value.searchWord = keywordText;
  getGoodsList();
};
// 查看视频
const videoShow = ref(false);
const openVideo = () => {
  videoShow.value = true;
};
const closeVideo = () => {
  videoShow.value = false;
};

// 选择分类
const selectType = (
  id: number,
  typeName: string,
  childrenType: Array<{ id: number; name: string }> = []
) => {
  const prevFirstTypeId = formData.value.firstTypeId;
  formData.value.firstTypeId = id;
  if (prevFirstTypeId !== id) {
    formData.value.secondTypeId = [];
  }
  typeId.value = id;
  typeLabel.value = typeName;
  childrenTypes.value = childrenType;
  getGoodsList();
};
// 刷新
const toDetails = (dataItem: any) => {
  console.log('点击商品详情:', dataItem);
  
  router.push({
    path: "/details",
    query: {
      id: dataItem.goodsId,
    },
  });
};
// 输入预算
const inputAmouont = (type: string) => {
  if (type === "min") {
    // 最小预算，限制最小0
    if (Number(formData.value.minAmouont) < 0) {
      formData.value.minAmouont = 0;
    } else {
      if (Number(formData.value.minAmouont) > Number(formData.value.maxAmouont)) {
        ElMessage.error("最低预算不能大于最高预算");
        formData.value.minAmouont = 0;
      } else if (Number(formData.value.minAmouont) > 100000000) {
        ElMessage.error("最低预算不能大于100000000");
        formData.value.minAmouont = 100000000;
      } else {
        formData.value.minAmouont = Number(formData.value.minAmouont);
      }
    }
  } else {
    // 最大预算，限制最大100000000
    if (Number(formData.value.maxAmouont) >= 100000000) {
      formData.value.maxAmouont = 100000000;
      ElMessage.error("最高预算不能大于100000000");
    } else {
      formData.value.maxAmouont = Number(formData.value.maxAmouont);
    }
  }
};

const hideAll = () => {

};
</script>

<template>
  <div class="commodity-page">
    <BaseHeaderMenuWhite bg-color="white" @headerSearch="headerSearch" />
    <!--商品分类-->
    <div class="service-class-box">
      <ServiceClass @selectType="selectType" :keyword="keyword" :formParams="formData" />
    </div>
    <!---->
    <div class="class-filter">
      <h2 class="title">{{ typeLabel }}</h2>
      <div class="tips">
        <p>凭借适合您品牌个性的徽标从人群中脱颖而出。</p>
        <span class="work" @click="openVideo">
          <img src="~/assets/class-work-icon.png" alt="" />
          如何工作的？
        </span>
      </div>
      <div class="filter-box">
        <FilterSelect selectLabel="服务选项" @selectConfirm="selectConfirm" @clearSetting="clearSetting(1)"
          :show-btns="childrenTypes.length > 0" @hideAll="hideAll">
          <div class="select-list">
            <p class="select-title">{{ typeLabel }}</p>
            <div class="select-list-item" v-if="childrenTypes.length > 0">
              <el-checkbox-group v-model="formData.secondTypeId">
                <el-checkbox v-for="item of showMoreList" :key="item.id" :label="item.name" :value="item.id">
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <el-empty v-else description="暂无更多服务选项" />
            <p @click="openMore" class="open-more"
              v-if="childrenTypes.length > 0 && childrenTypes.length > 8 && !showMore">
              <span>+ {{ childrenTypes.length - 8 }} 查看更多</span><img src="~/assets/open-icon.png" alt="" />
            </p>
            <p v-if="showMore" class="open-more" @click="showMore = false">
              <span>收起</span><img src="~/assets/open-icon.png" alt="" style="transform: rotate(180deg)" />
            </p>
          </div>
        </FilterSelect>
        <FilterSelect selectLabel="卖家信息" @selectConfirm="selectConfirm" @clearSetting="clearSetting(2)"
          @hideAll="hideAll">
          <div class="select-list" v-if="reset">
            <p class="select-title">卖家级别</p>
            <div class="select-list-item">
              <div class="item" v-for="item of salerLevels" :key="item.value">
                <el-checkbox @change="salerLevelsChange(item.value)" :model-value="formData.sellerLevel && formData.sellerLevel.includes(item.value)
                  " size="large">
                  <span class="label">{{ item.label }}</span>
                </el-checkbox>
              </div>
            </div>
            <p class="line"></p>
            <p class="select-title">卖家状态</p>
            <div class="select-list-item">
              <div class="item" v-for="item of online" :key="item.value">
                <el-checkbox @change="onlineChange(item.value)"
                  :model-value="formData.sellerOnline && formData.sellerOnline.includes(item.value)" size="large">
                  <span class="label">{{ item.label }}</span>
                </el-checkbox>
              </div>
            </div>
          </div>
        </FilterSelect>
        <FilterSelect selectLabel="预算" @selectConfirm="selectConfirm" @clearSetting="clearSetting(3)"
          @hideAll="hideAll">
          <div class="budget">
            <div class="budget-input">
              <span>￥</span>
              <input type="number" v-model="formData.minAmouont" placeholder="最低预算" @input="inputAmouont('min')" />
            </div>
            <span class="to">~</span>
            <div class="budget-input">
              <span>￥</span>
              <input type="number" v-model="formData.maxAmouont" placeholder="最高预算" @input="inputAmouont('max')" />
            </div>
          </div>
        </FilterSelect>
        <!-- <SelectRadio /> -->
        <div class="list-size">
          <span class="size">{{ total }} 个结果</span>
          <span class="size-title">排序方式：</span>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              {{ formData.orderBy === 1 ? "最畅销" : "最低价" }}
              <el-icon class="el-icon--right" size="14">
                <ArrowDown />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="switchOrder(1)">最畅销</el-dropdown-item>
                <el-dropdown-item @click="switchOrder(2)">最低价</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="user-select">
      <template v-if="isSelectGoodsType">
        <span v-for="item of selectGoodsTypeList" :key="item.id">{{ item.name }}
          <el-icon style="cursor: pointer" @click="delSelect(1, item)">
            <Close />
          </el-icon></span>
      </template>
      <template v-if="selectSalerLevels.length > 0">
        <span v-for="item of selectSalerLevels" :key="item.value">{{ item.label }}
          <el-icon style="cursor: pointer" @click="delSelect(2, item)">
            <Close />
          </el-icon></span>
      </template>
      <template v-if="selectOnline.length > 0">
        <span v-for="item of selectOnline" :key="item.value">{{ item.label }}
          <el-icon style="cursor: pointer" @click="delSelect(3, item)">
            <Close />
          </el-icon></span>
      </template>
      <span v-if="formData.minAmouont || formData.maxAmouont">¥{{ formData.minAmouont || "0" }} - ¥{{
        formData.maxAmouont ||
        "~" }}
        <el-icon style="cursor: pointer" @click="delSelect(4)">
          <Close />
        </el-icon></span>
    </div>
    <div class="commodity-list">
      <template v-if="records.length > 0">
        <RecommendingItem v-for="item of records" :key="item.id" :dataItem="item" @refresh="toDetails"
          type="commodity" />
      </template>
      <div v-else-if="loading" class="loading-box">
        <div class="loading-content">
          <l-tail-chase size="70" speed="1.75" color="#1dbf73"></l-tail-chase>
        </div>
      </div>
      <div class="empty-box" v-if="!loading && records.length === 0 && total === 0">
        <el-empty description="暂无商品" />
      </div>
    </div>
    <div class="paging-box" v-if="records.length > 0">
      <el-pagination layout="prev, pager, next" :page-size="20" :current-page="formData.pageNum" :total="total"
        @currentChange="currentChange" />
    </div>
  </div>
  <BaseFooter />
  <DialogViewVideo v-if="videoShow" @close="closeVideo" />
</template>

<style scoped lang="scss">
.commodity-page {
  width: 100%;
}

.body {
  background: linear-gradient(180deg, #ffffff 0%, #f9f9f9 15%);
}

.service-class-box {
  padding-top: 80px;
}

.class-filter {
  width: 1200px;
  margin: 24px auto 0;

  .title {
    color: #191e28;
    font-size: 30px;
    margin-bottom: 12px;
  }

  .tips {
    display: flex;
    align-items: center;

    p {
      font-size: 15px;
      color: rgba(25, 30, 40, 0.6);
    }

    .work {
      display: flex;
      align-items: center;
      color: rgba(25, 30, 40, 0.6);
      border-left: 1px solid rgba(25, 30, 40, 0.12);
      padding-left: 12px;
      margin-left: 12px;
      cursor: pointer;

      &:hover {
        color: #1dbf73;
      }

      img {
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
    }
  }
}

.filter-box {
  display: flex;
  align-items: center;
  margin-top: 24px;

  &>div {
    margin-right: 16px;
  }

  .list-size {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .size {
      color: rgba(25, 30, 40, 0.48);
      border-right: 1px solid rgba(25, 30, 40, 0.12);
      padding-right: 12px;
      margin-right: 12px;
      line-height: 14px;
    }

    .size-title {
      color: rgba(25, 30, 40, 0.48);
    }

    .value {
      display: flex;
      align-items: center;

      img {
        width: 16px;
        height: 16px;
      }
    }

    .el-dropdown-link {
      line-height: 26px;
      cursor: pointer;
      display: flex;
      align-items: center;
    }
  }
}

.commodity-list {
  width: 1200px;
  min-height: 600px;
  margin: 24px auto 0;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;

  .empty-box {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 500px;
  }

  .loading-box {
    width: 100%;
    height: calc(100vh - 200px);
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      width: 600px;
      height: 337px;
    }
  }
}

.paging-box {
  display: flex;
  justify-content: center;
  padding-bottom: 36px;
  padding-top: 12px;
}

.user-select {
  width: 1200px;
  margin: 0 auto;
  padding: 12px 0;
  display: flex;
  flex-wrap: wrap;

  span {
    padding: 5px 12px;
    display: flex;
    align-items: center;
    border-radius: 6px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    color: #191e28;
    margin-right: 12px;
    margin-bottom: 5px;

    i {
      margin-left: 6px;
      color: rgba(25, 30, 40, 0.48);
    }
  }
}
</style>
<style lang="scss">
.paging-box .el-pagination button:disabled {
  background: none;
}

.paging-box .el-pagination button.is-first {
  margin-right: 6px;
}

.paging-box .el-pagination button.is-last {
  background: none;

  &:hover {
    font-weight: bold;
    color: #191e28;
  }
}

.paging-box .el-pager li {
  background: none;
  width: 36px;
  height: 36px;
  margin-right: 6px;

  &:hover {
    font-weight: bold;
    color: #191e28;
  }
}

.paging-box .el-pager li.is-active {
  background: #fff;
  box-shadow: 0 0 16px 0 rgba(11, 13, 18, 0.06);
  border-radius: 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  color: #191e28;
}

.filter-box .el-checkbox {
  width: 40%;
  margin-bottom: 10px;
}

.filter-box .el-checkbox__inner {
  width: 20px !important;
  height: 20px !important;
  border-radius: 4px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  display: flex;
}

.filter-box .el-checkbox__input.is-checked .el-checkbox__inner {
  width: 20px;
  height: 20px;
  background: #1dbf73;
  border: 1px solid #1dbf73;
}

.filter-box .el-checkbox__inner:after {
  top: 3px;
  left: 7px;
}

.filter-box .el-checkbox__label {
  color: #191e28 !important;
}
</style>
